import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.URL;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/* 
 * TODO ---
 * This is a very inefficient solution to the video problem, even though it's the only one that seems to work.
 * If you get time, can you please try to make the MjpegStreamer work?
 */

public class JpegFetchSend implements Runnable {
	//class-level constants
	private static final int MAX_CLIENTS = 15;
	private static final int FETCH_RATE = (1000 / 100); //e.g. per second
	
	//have we requested to stop
	private boolean stopRequested = false;
	
	//network-related members : jpeg host
	private final URL jpgHostUrl;

	//network-related members : jpeg host
	private final int clientPort;
	private final ServerSocket clientServerSocket;
	
	//image frame members
	private BufferedImage curFrm;
	private BufferedImage lastFrm;
	
	//the connected output streams
	//TODO
	
	//the ScheduledExecutorService for this service and related members
	private final ScheduledExecutorService scheduledJpegSvc = Executors.newScheduledThreadPool(1);
	private final Runnable jpegFetchSendRunnable = new Runnable() {
		public void run() {
			System.out.println("Fetch a frame!");
			//do the thing
		}
	};
	private final ScheduledFuture jpegFetchSendHandle;
	
	public JpegFetchSend(int jpgClientPort, URL jpgHost) throws IOException {
		this.jpgHostUrl = jpgHost;
		this.clientPort = jpgClientPort;
		this.clientServerSocket = new ServerSocket(this.clientPort);
		
		//finally, begin running the scheduler
		this.jpegFetchSendHandle = this.scheduledJpegSvc.scheduleAtFixedRate
				(this.jpegFetchSendRunnable, JpegFetchSend.FETCH_RATE, JpegFetchSend.FETCH_RATE, TimeUnit.MILLISECONDS);
	}
	
	public void run() {
		//initialize whatever
		
		//set up the scheduled runner
		
		//accept connections and deal with whatever clients have left
		while(!this.stopRequested) {
			//get a new client
			
			//clean out closed clients
			
			//add the new client to the array of clients
			
		}
		
		//cancel any scheduled tasks. close any remaining open resources.
		
	}
	
	public synchronized void requestStop() {
		this.stopRequested = true;
	}
}
